package com.leyou.order.service;

import com.leyou.common.auth.pojo.UserHolder;
import com.leyou.common.exception.pojo.ExceptionEnum;
import com.leyou.common.exception.pojo.LyException;
import com.leyou.common.utils.IdWorker;
import com.leyou.item.entity.Evaluate;
import com.leyou.user.client.UserClient;
import com.leyou.user.entity.UserInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class EvaluateService {
    @Autowired
    private MongoTemplate mongoTemplate;
    @Autowired
    private OrderService orderService;
    @Autowired
    private UserClient userClient;
    public void insertEvaluate(Evaluate evaluate) {
        IdWorker idWorker = new IdWorker();
        evaluate.setId(idWorker.nextId());//用雪花算法保证MongoDB数据不会被覆盖
//        Long userId = 32L;//测试用
        Long userId = UserHolder.getUserId();//正式代码用
        evaluate.setUid(userId);//测试用
        UserInfo userInfo = userClient.getUserInfo(userId);
        evaluate.setUserImage(userInfo.getImage());
//        evaluate.setUserImage("xxxxxxxx.jpg");测试用
        evaluate.setNickName(userInfo.getNickName());
        try {
            mongoTemplate.save(evaluate);
        } catch (Exception e) {
            throw new LyException(ExceptionEnum.INSERT_OPERATION_FAIL);
        }

    }

    public void insertEvaluateList(List<Evaluate> evaluateList) {
//        List<OrderDetail> detailList = orderVO.getDetailList();
//        List<Evaluate> evaluateList = BeanHelper.copyWithCollection(detailList, Evaluate.class);
        try {
            evaluateList.forEach(evaluate -> {
                insertEvaluate(evaluate);
            });
        } catch (Exception e) {
            throw new LyException(501,"添加评价失败");
        }
        //todu修改订单状态
        Evaluate evaluate = evaluateList.get(0);
        Long orderId = evaluate.getOrderId();
        orderService.updateOrderStatusById(orderId);
    }

    public List<Evaluate> queryEvaluateListBySkuId(Long id) {
        Query query=new Query(Criteria.where("skuId").is(id));
        List<Evaluate> evaluateList = mongoTemplate.findAll(Evaluate.class);
        return evaluateList;
    }
}
